package com.gmlive.common.ui.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.text.InputType;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.View;

import androidx.appcompat.widget.AppCompatEditText;

import com.gmlive.common.ui.R;
import com.gmlive.common.ui.util.ResHelper;


public class PasswordEditText extends AppCompatEditText {
    public static final int LENGTH = 4;

    private static final float PADDING = 12.5f;

    /**
     * 构造函数
     *
     * @param context
     */
    public PasswordEditText(Context context) {
        this(context, null);
    }

    /**
     * 构造函数
     *
     * @param context
     * @param attrs
     */
    public PasswordEditText(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    /**
     * 构造函数
     *
     * @param context
     * @param attrs
     * @param defStyleAttr
     */
    public PasswordEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        prepareView(context);
    }

    private Paint mPaint = null;
    private int size = 0;
    private Drawable enable = null;
    private Drawable disable = null;

    /**
     * 初始化view
     *
     * @param context
     */
    private void prepareView(Context context) {
        setInputType(InputType.TYPE_CLASS_NUMBER);
        setLongClickable(false);
        setTextIsSelectable(false);
        setCursorVisible(false);
        setBackgroundDrawable(null);

        size = context.getResources().getDimensionPixelSize(R.dimen.ik_pwd_input_item_size);
        enable = context.getResources().getDrawable(R.drawable.ik_pwd_input_item_filled);
        enable.setBounds(0, 0, size, size);
        disable = context.getResources().getDrawable(R.drawable.ik_pwd_input_item_normal);
        disable.setBounds(0, 0, size, size);
        int sp = context.getResources().getDimensionPixelOffset(R.dimen.ik_pwd_input_text_size);
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setTextSize(sp);
        mPaint.setColor(Color.rgb(0x35, 0x35, 0x35));
        mPaint.setTextAlign(Paint.Align.CENTER);

        ((GradientDrawable) enable).setColor(ResHelper.getThemeColor(getContext()));
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int heightMode = View.MeasureSpec.getMode(heightMeasureSpec);
        int heightSize;
        int widthSize = calculateWidth();

        switch (heightMode) {
            case View.MeasureSpec.EXACTLY:
                heightSize = View.MeasureSpec.getSize(heightMeasureSpec);
                break;
            default:
                heightSize = ResHelper.dip2px(getContext(), 36);
                break;
        }
        setMeasuredDimension(widthSize, heightSize);
    }

    @Override
    protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
        super.onTextChanged(text, start, lengthBefore, lengthAfter);
        //开始处理文本输入
        if (null == mPasswordText) {
            return;
        }
        int len = mPasswordText.length();
        if (len < mPasswordLength && text.length() > 0 && TextUtils.isDigitsOnly(text)) {
            mPasswordText.append(text);
            isNew = true;
            notifyObservers();
        }
        //清除输入
        if (text.length() > 0) {
            setText("");
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        removeCallbacks(mTimer);
    }

    private int calculateWidth() {
        return mPasswordLength * (size + ResHelper.dip2px(getContext(), PADDING) * 2);
    }

    /**
     * 返回密码
     *
     * @return
     */
    public String getPasswordText() {
        if (mPasswordText.length() < mPasswordLength) {
            return "";
        }
        return mPasswordText.toString();
    }

    private int mPasswordLength = LENGTH;

    /**
     * 设置文本框长度
     *
     * @param mPasswordLength 文本框长度
     */
    public void setPasswordLength(int mPasswordLength) {
        this.mPasswordLength = mPasswordLength;
        requestLayout();
    }

    public int getPasswordLength() {
        return mPasswordLength;
    }

    private IOnInputListener listener;

    /**
     * 设置监听器
     *
     * @param listener
     */
    public void setListener(IOnInputListener listener) {
        this.listener = listener;
    }

    /**
     * 回调监听器
     */
    private void notifyObservers() {
        if (null != listener) {
            String password = getPasswordText();
            listener.onInput(!TextUtils.isEmpty(password), password);
        }
        //数字显示状态时间计时
        removeCallbacks(mTimer);
        if (this.mPasswordText.length() > 0 && isNew) {
            postDelayed(mTimer, 500);
        }
    }

    private volatile boolean isNew = false;

    private Runnable mTimer = new Runnable() {
        @Override
        public void run() {
            timer();
        }
    };

    /**
     * 执行timer，改变状态
     */
    private void timer() {
        isNew = false;
        postInvalidate();
    }

    /**
     * 清空数据
     */
    public void clear() {
        int len = mPasswordText.length();
        if (len > 0) {
            mPasswordText.delete(0, len);
            notifyObservers();
        }
        setText("");
    }

    private StringBuffer mPasswordText = new StringBuffer();

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        int len = mPasswordText.length();
        if (keyCode == KeyEvent.KEYCODE_DEL && len > 0) {
            mPasswordText.deleteCharAt(len - 1);
            postInvalidate();
            notifyObservers();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //绘制
        int vWidth = Math.min(getMeasuredHeight(), getMeasuredWidth() / mPasswordLength);
        int hSpace = getMeasuredWidth() / mPasswordLength - vWidth;
        int vSpace = (getMeasuredHeight() - size) >> 1;
        int pLength = mPasswordText.length();
        canvas.save();
        for (int i = 0; i < mPasswordLength; i++) {
            canvas.translate((vWidth + hSpace - size) >> 1, vSpace);
            if (i < pLength) {
                if (i == pLength - 1 && isNew) {//显示数字
                    String c = mPasswordText.substring(i);
                    canvas.drawText(c, size >> 1, size, mPaint);
                } else {//显示已输入
                    enable.draw(canvas);
                }
            } else {//显示未输入
                disable.draw(canvas);
            }
            canvas.translate((vWidth + hSpace + size) >> 1, -vSpace);
        }
        canvas.restore();
    }

    /**
     * 监听器
     */
    public interface IOnInputListener {
        /**
         * 输入回调
         *
         * @param filled,  表示是否已经输入完成
         * @param text, 已经输入当文本内容
         */
        void onInput(boolean filled, String text);
    }
}
